package com.youlu.campus.admin.annotation;

import lombok.extern.slf4j.Slf4j;
import org.springframework.core.LocalVariableTableParameterNameDiscoverer;
import org.springframework.expression.EvaluationContext;
import org.springframework.expression.Expression;
import org.springframework.expression.ExpressionParser;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.spel.support.StandardEvaluationContext;

import java.lang.reflect.Method;

/**
 * @Author dengbo
 * @Date 2021/3/5 5:42 下午
 */
@Slf4j
public class AnnotationResolverUtil {
    private static ExpressionParser parser = new SpelExpressionParser();
    private static LocalVariableTableParameterNameDiscoverer discoverer = new LocalVariableTableParameterNameDiscoverer();

    /**
     * 解析 spel 表达式
     *
     * @param spel          表达式
     * @param method        方法
     * @param arguments     参数
     * @return 执行spel表达式后的结果
     */
    public static Object parseSPEL(String spel, Method method, Object[] arguments) {
        String[] params = discoverer.getParameterNames(method);
        EvaluationContext context = new StandardEvaluationContext();
        for (int len = 0; len < params.length; len++) {
            context.setVariable(params[len], arguments[len]);
        }
        try {
            Expression expression = parser.parseExpression(spel);
            return expression.getValue(context);
        } catch (Exception e) {
            log.warn(" AnnotationResolver parse spel error {}", e);
            return null;
        }
    }
}
